const BaseService = require('./base_service.js');
const DeviceModel = require('../model/device_model.js');
const StoreModel = require('../model/store_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class DeviceManagementService extends BaseService {

  /**
   * 添加设备
   */
  async addDevice(input) {
    // 检查设备是否存在
    const existingDevice = await DeviceModel.getOne({ 
      name: input.name,
      storeId: input.storeId 
    });
    
    if (existingDevice) {
      throw new Error('设备名称已存在');
    }

    // 创建设备数据
    const deviceData = {
      _pid: input.storeId || 'default_store',
      storeId: input.storeId,
      name: input.name,
      type: input.type,
      category: input.category,
      code: input.code || input.name,
      location: typeof input.location === 'string' ? input.location : JSON.stringify(input.location),
      price: input.price ? input.price * 100 : 0, // 前端传元，转为分
      status: DeviceModel.STATUS.AVAILABLE,
      isOnline: false,
      switchStatus: false,
      createTime: timeUtil.time(),
      updateTime: timeUtil.time()
    };
    
    // 处理MQTT配置
    if (input.mqttTopic) {
      const topicParts = input.mqttTopic.split('/').filter(p => p);
      if (topicParts.length >= 4) {
        deviceData.appId = topicParts[0];
        deviceData.deviceKey = topicParts[1];
        deviceData.deviceMAC = topicParts[2];
        deviceData.publishTopic = input.mqttTopic;
      }
    }

    const device = await DeviceModel.insert(deviceData);
    
    return {
      deviceId: device._id,
      message: '设备添加成功'
    };
  }

  /**
   * 删除设备
   */
  async deleteDevice(deviceId) {
    // 检查设备是否存在
    const device = await DeviceModel.getOne({ _id: deviceId });
    if (!device) {
      throw new Error('设备不存在');
    }

    // 物理删除（根据实际需求可以改为软删除）
    await DeviceModel.delete({ _id: deviceId });

    return { message: '设备删除成功' };
  }

  /**
   * 更新设备
   */
  async updateDevice(deviceId, input) {
    // 检查设备是否存在
    const device = await DeviceModel.getOne({ _id: deviceId });
    if (!device) {
      throw new Error('设备不存在');
    }

    // 准备更新数据
    const updateData = {
      updateTime: timeUtil.time()
    };
    
    // 只更新提供的字段
    if (input.name) updateData.name = input.name;
    if (input.type) updateData.type = input.type;
    if (input.category) updateData.category = input.category;
    if (input.code) updateData.code = input.code;
    if (input.location) updateData.location = typeof input.location === 'string' ? input.location : JSON.stringify(input.location);
    if (input.price !== undefined) updateData.price = input.price * 100; // 前端传元，转为分
    if (input.status !== undefined) updateData.status = input.status;
    
    // 处理MQTT配置
    if (input.mqttTopic) {
      const topicParts = input.mqttTopic.split('/').filter(p => p);
      if (topicParts.length >= 4) {
        updateData.appId = topicParts[0];
        updateData.deviceKey = topicParts[1];
        updateData.deviceMAC = topicParts[2];
        updateData.publishTopic = input.mqttTopic;
      }
    }

    await DeviceModel.edit({ _id: deviceId }, updateData, false);

    return { message: '设备更新成功' };
  }

  /**
   * 获取设备列表
   */
  async getDeviceList(input) {
    // 构建查询条件
    let where = {};
    
    if (input.storeId) {
      where.storeId = input.storeId;
    }
    
    if (input.type) {
      where.type = input.type;
    }
    
    if (input.status !== undefined) {
      where.status = input.status;
    }

    // 获取字段列表
    const fields = 'name,type,category,code,location,price,status,isOnline,switchStatus,appId,deviceKey,deviceMAC,publishTopic,createTime,updateTime';
    
    // 排序
    const orderBy = { createTime: -1 };

    // 分页查询
    const list = await DeviceModel.getAll(where, fields, orderBy, input.size || 100, false);

    // 如果需要搜索
    if (input.search) {
      const searchRegex = new RegExp(input.search, 'i');
      return list.filter(device => 
        device.name && searchRegex.test(device.name) ||
        device.code && searchRegex.test(device.code) ||
        device.category && searchRegex.test(device.category)
      ).slice((input.page - 1) * (input.size || 20), input.page * (input.size || 20));
    }

    // 分页切片
    const startIndex = (input.page - 1) * (input.size || 20);
    const endIndex = startIndex + (input.size || 20);
    
    return {
      list: list.slice(startIndex, endIndex),
      total: list.length,
      page: input.page || 1,
      size: input.size || 20
    };
  }
}

module.exports = DeviceManagementService;
